package cn.iluwen.airline.Config.interceptor;

import cn.iluwen.airline.Services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 用户认证拦截器
 * 通过Cookie中的userId进行认证
 */
public class UserAuthInterceptor implements HandlerInterceptor {
    
    @Autowired
    private UserService userService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从Cookie中获取userId
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("userId".equals(cookie.getName())) {
                    String userId = cookie.getValue();
                    // 验证用户ID是否有效
                    if (userId != null && userService.getUserById(userId) != null) {
                        // 将userId放入请求属性中，便于后续使用
                        request.setAttribute("userId", userId);
                        return true; // 认证通过
                    }
                    break;
                }
            }
        }
        
        // 认证失败，重定向到登录页面或返回401错误
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"code\":401,\"message\":\"请先登录\",\"data\":null}");
        return false;
    }
} 